//
//  RwData.m
//  rwipad
//
//  Created by S W Consultancy on 26/08/2011.
//  Copyright 2011 SW Consultancy. All rights reserved.
//

#import "RwData.h"

@implementation RwData

-(NSDictionary*)dict{
    return dict;
}

+ (RwData *)singleton:(NSString *)pListName
{
    static NSMutableDictionary* gDict=NULL;
    @synchronized(self)
    {
        if (gDict==NULL) {// create it first time
            gDict = [[NSMutableDictionary alloc] init];
        }
        RwData* instance = [gDict objectForKey:pListName];
        if (instance==nil) { // add if does not exist
            instance = [[self alloc] initWithName:pListName];
            [gDict setValue:instance forKey:pListName];
        }
    }
    return [gDict objectForKey:pListName];
}

-(id)initWithName:(NSString *)pListName{
    //NSLog(@"initWithName %@", pListName);
    
    short_name = pListName;
    //NSLog(@"short_name %@", short_name);

    long_name = [pListName stringByAppendingString:@".plist"];
    //NSLog(@"long_name %@", long_name);
    
    root = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    //NSLog(@"root %@", root);
    
    NSString *path = nil;
    save_path = [root stringByAppendingPathComponent:long_name];
    NSLog(@"save_path %@", save_path);
    bundle_path = [[NSBundle mainBundle] pathForResource:short_name ofType:@"plist"];
    //NSLog(@"bundle_path %@", bundle_path);
    if ([[NSFileManager defaultManager] fileExistsAtPath:save_path]) {
        path = save_path; // previously saved file
    }
    else if ([[NSFileManager defaultManager] fileExistsAtPath:bundle_path]) {
        path = bundle_path; // default bundle file
    }
    //NSLog(@"path %@", path);

    if (path){
        NSData *data = [[NSFileManager defaultManager] contentsAtPath:path];    
        NSString *error = nil;
        NSPropertyListFormat format;
        dict = [NSPropertyListSerialization propertyListFromData:data mutabilityOption:NSPropertyListMutableContainersAndLeaves format:&format errorDescription:&error];
        if (error){
            NSLog(@"error %@", error);
        }
    }
    else {
        dict = [[NSMutableDictionary alloc] init]; // if no file: start with an empty one
    }
    self = [super init];
    return self;
}

-(NSString*)read: (NSString*)key{
    NSString* result = [dict valueForKey:key];
    //NSLog(@"read key:%@ value:%@", key, result);
    return result;
}

-(NSString*)readAtIndex:(int)key{
    NSString* result = [dict valueForKey:[NSString stringWithFormat:@"%d", key]];
    //NSLog(@"readAtIndex key:%d value:%@", key, result);
    return result;
}

-(int)readAsInt: (NSString*)key{
    int result = [[dict valueForKey:key] intValue];
    //NSLog(@"read as int key:%@ value:%d", key, result);
    return result;
}

-(void)write: (NSString*)key :(NSString*)value{
    //NSLog(@"write key:%@ value:%@", key, value);

    [dict setValue:value forKey:key]; 
    [self save]; // save after every write
}

-(void)writeAsInt:(NSString *)key :(int)value{
    //NSLog(@"writeAsInt key:%@ value:%d", key, value);

    [dict setValue:[NSString stringWithFormat:@"%d", value] forKey:key]; 
    [self save]; // save after every write
}

-(void)insertAtEnd :(NSString*)value{
    //NSLog(@"insertAtEnd value:%@ at key:%d", value, [dict count]);

    [dict setValue:value forKey:[NSString stringWithFormat:@"%d", [dict count]]]; 
    [self save]; // save after every write
}

-(void)remove: (NSString*)key{
    [dict removeObjectForKey:key];
}

-(void)removeAtIndex: (int)key{ // messy, an array would be better!
    int max = [dict count];
    for (int i=1; i<max; i++) {
        if (i>key) {             // shuffle values down
            [dict setValue:[self readAtIndex:i] forKey:[NSString stringWithFormat:@"%d", i-1]];
        }
    }
    if (max){ // delete last
        [dict removeObjectForKey:[NSString stringWithFormat:@"%d", max-1]];
        [self save]; // save after every write
    }
}

-(void)insertAtIndex:(int)key :(NSString *)value{
    NSLog(@"insertAtIndex NYI");
}

-(void)writeAtIndex:(int)key :(NSString *)value{
    //NSLog(@"writeAtIndex key:%d value:%@", key, value);

    [dict setValue:value forKey:[NSString stringWithFormat:@"%d", key]]; 
    [self save]; // save after every write
}

-(void)save{
    //NSLog(@"save");
    
    NSString *error;
    NSData *data = [NSPropertyListSerialization dataFromPropertyList:dict format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];
    if (error){
        NSLog(@"%@", error);
    }
    if(data) {
        [data writeToFile:save_path atomically:YES];
    }
}

-(void)empty{
    //NSLog(@"empty");

    [dict removeAllObjects];
    [self save];
}

-(int)count{
    return [dict count];
}


@end
